package Algorithm

import (
	"errors"
	"fmt"
	"lht-go-plugins/LhtSettings"
	"lht-go-plugins/internal/core"
	"sync"
)

type DeviceChannel struct {
	ChannelID int
	DataCh    chan []byte
}

type Device struct {
	DeviceID string
	Channels map[int]*DeviceChannel
}
type AlgoPlugin struct {
	*core.BasePlugin
	conf    LhtSettings.AlgoConfig
	mu      sync.RWMutex
	devices map[string]*Device
}

func NewAlgoPlugin(cfg *LhtSettings.AlgoConfig) *AlgoPlugin {
	return &AlgoPlugin{
		BasePlugin: core.NewBasePlugin("algorithm", cfg.MaxCacheSize),
		devices:    make(map[string]*Device),
	}
}

func (r *AlgoPlugin) Init(cfg any) error {
	conf, ok := cfg.(*LhtSettings.AlgoConfig)
	if !ok {
		return errors.New("invalid config type: expected *RedisConfig")
	}
	if conf == nil {
		return errors.New("redis config missing")
	}
	r.conf = *conf
	return nil
}

func (r *AlgoPlugin) Start() error {
	return r.BasePlugin.Start(r.handleData)
}

func (r *AlgoPlugin) handleData(data []byte) {

	fmt.Printf("[algorithm] recv data: %s\n", string(data))

	msg := decodeAlgoData(data)
	if msg == nil {
		fmt.Println("dispatch decode failed")
		return
	}

	r.dispatch(msg.DeviceID, msg.ChannelID, msg.Payload)
}
